import { removeRule, rule } from '@/services/ant-design-pro/api';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useLocation, useRequest } from '@umijs/max';
import { Button, Drawer, Input, message, Image } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { detailList, delDetail } from '@/services/ant-design-pro/source';
import dayjs from 'dayjs';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  // const paramData:any = useLocation().state
  const param = localStorage.getItem('idArray');
  const paramData = JSON.parse(param);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const [messageApi, contextHolder] = message.useMessage();

  const { run: delRun, loading } = useRequest(removeRule, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('Deleted successfully and will refresh soon');
    },
    onError: () => {
      messageApi.error('Delete failed, please try again');
    },
  });

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title:'ID',
      dataIndex: 'id',
      tip: 'The rule name is the unique key',
      hideInSearch: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: '封面',
      dataIndex: 'cover',
      hideInSearch: true,
      render: (_, record:any) => {
        return (
          record.cover === null ? '-' :
          <Image
            width={100}
            src={record.cover}
          />
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: (
            <FormattedMessage
              id="pages.searchTable.nameStatus.default"
              defaultMessage="Shut down"
            />
          ),
          status: 'Default',
        },
        1: {
          text: (
            <FormattedMessage id="pages.searchTable.nameStatus.online" defaultMessage="Running" />
          ),
          status: 'Success',
        },
      },
    },
    {
      title: '资源',
      dataIndex: 'source',
      valueType: 'textarea',
      hideInSearch: true,
      render: (_, record:any) => [
          <a key={record.source} href={record.source} target="_blank">
            查看
          </a>,
      ],
    },
    {
      title: '简介',
      dataIndex: 'detail',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '页数',
      dataIndex: 'page',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'ctime',
      valueType: 'textarea',
      hideInSearch: true,
      renderText: (_, record:any) =>
      `${dayjs(record.ctime).format('YYYY-MM-DD HH:mm:ss')}`,
    },
    {
      title: '修改时间',
      dataIndex: 'mtime',
      valueType: 'textarea',
      hideInSearch: true,
      renderText: (_, record:any) =>{
        return record.mtime === null ? '' : `${dayjs(record.mtime).format('YYYY-MM-DD HH:mm:ss')}`
      }
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <UpdateForm
          key={Math.random()}
          reload={actionRef.current?.reload} param={paramData} values = {record}
        />,
        <Button type="link" onClick={()=>handleRemove(record)} danger>删除</Button>,
      ],
    },
  ];

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record: any) => {
    const res = await delDetail({id: record.id})
    if(res.code === 0){
      messageApi.success('删除成功')
      actionRef.current?.reload()
    }else{
      messageApi.error('删除失败')
    }
  };

  return (
    <PageContainer title={paramData.collectName}>
      {contextHolder}
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={() => [<CreateForm key="create" reload={actionRef.current?.reload} param={paramData} />]}
        request={async (params:{
          pageSize: number;
          current: number;
          name: string;
        })=>{
          const msg = await detailList({
            releaseId: paramData.id,
            name: params.name ?? '',
            pageNo: params.current-1,
            pageSize: params.pageSize,
          })
          return {
            data:msg.obj.list,
            success:msg.obj.total,
          }
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default TableList;
